<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas</title>
    <style></style>
  </head>
  <body>
    <div class="container">
      <canvas id="demo"></canvas>
    </div>

    <script>
      ;(function () {
        const $canvas = document.querySelector('#demo')
        $canvas.width = 600
        $canvas.height = 600
        $canvas.style.border = '1px solid #cccccc'

        const context = $canvas.getContext('2d')

        // 封装自定义绘制直线函数
        function drawLine(
          context,
          lineWidth,
          strokeStyle,
          [moveX, moveY, toX, toY]
        ) {
          // 用来清除绘制状态，如果不设置 strokeStyle lineWidth ,则默认继承上一次绘制的状态，否则以当前设置为准
          context.beginPath()

          context.lineWidth = lineWidth
          context.strokeStyle = strokeStyle

          context.moveTo(moveX, moveY)
          context.lineTo(toX, toY)
          context.stroke()
        }

        drawLine(context, 2, 'red', [100, 100, 300, 100])

        drawLine(context, 4, 'green', [100, 200, 300, 200])

        drawLine(context, 6, 'yellow', [100, 300, 300, 300])
      })()
    </script>
  </body>
</html>
